global r4data "/.../data"
global output "/.../output"
set more off
set linesize 255

*----------------------------------------------------------------------------------------------------
* Author: Dhiren Patki
*
* This program computes the share of retirement pre-65 and post-68 separately for treated and control
* samples for workers inrange(56,64) at the time of the feeze
*----------------------------------------------------------------------------------------------------

*Read in stacked cohort cells 
use "$r4data/wkerpanel_m", clear

bysort idvar: egen plan_r_age_av = mean(plan_r_age)

merge 1:1 group firmid year sex_enc age_at_c source_at_cm5 tenure_cm5 using $r4data/analysis_sampflag, keepus(pw_samp_age5 invpwt_c_size5)

*retirement age bins

gen ret_pre65 = inrange(age_ret,50,64)
gen ret_post65 = inrange(age_ret,65,.)
gen ret_pre68 = inrange(age_ret,50,67)
gen ret_post68 = inrange(age_ret,68,.)

matrix stats = J(4,3,.)

*control pre-65 retirement share
sum ret_pre65 [aw=invpwt_c_size5] if pw_samp_age5==/*redacted*/ & inrange(k,/*redacted*/) & treat_flag==/*redacted*/
matrix stats[1,1] = r(mean)
local se = sqrt(r(Var)/r(N))
matrix stats[1,2] = `se'
matrix stats[1,3] = r(N)

*treated pre-65 retirement share
sum ret_pre65 [aw=invpwt_c_size5] if pw_samp_age5==1 & inrange(k,1,12) & treat_flag==1
matrix stats[2,1] = r(mean)
local se = sqrt(r(Var)/r(N))
matrix stats[2,2] = `se'
matrix stats[2,3] = r(N)

*control post-68 retirement share
sum ret_post68 [aw=invpwt_c_size5] if pw_samp_age5==1 & inrange(k,1,12) & treat_flag==0
matrix stats[3,1] = r(mean)
local se = sqrt(r(Var)/r(N))
matrix stats[3,2] = `se'
matrix stats[3,3] = r(N)

*treated post-68 retirement share
sum ret_post68 [aw=invpwt_c_size5] if pw_samp_age5==1 & inrange(k,1,12) & treat_flag==1
matrix stats[4,1] = r(mean)
local se = sqrt(r(Var)/r(N))
matrix stats[4,2] = `se'
matrix stats[4,3] = r(N)

clear
svmat stats
rename stats1 mean
rename stats2 se
rename stats3 N
gen treat = 0
replace treat=1 if inlist(_n,2,4)
gen var = ""
replace var = "Share retiring before 65" if _n<=2
replace var = "Share retiring after 68" if _n>2
order var treat N mean se 
export delimited using "$output/ret-share-by-age-5664.csv", datafmt replace






